package com.xlw.model;

import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

import com.xlw.model.Photo;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** 
 * DAO for table PHOTO.
*/
public class PhotoDao extends AbstractDao<Photo, Long> {

    public static final String TABLENAME = "PHOTO";

    /**
     * Properties of entity Photo.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
        public final static Property Uri = new Property(1, String.class, "uri", false, "URI");
        public final static Property TakeDate = new Property(2, java.util.Date.class, "takeDate", false, "TAKE_DATE");
        public final static Property Title = new Property(3, String.class, "title", false, "TITLE");
        public final static Property About = new Property(4, String.class, "about", false, "ABOUT");
        public final static Property LocationId = new Property(5, long.class, "locationId", false, "LOCATION_ID");
    };

    private DaoSession daoSession;

    private Query<Photo> location_PhotosQuery;

    public PhotoDao(DaoConfig config) {
        super(config);
    }
    
    public PhotoDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /** Creates the underlying database table. */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'PHOTO' (" + //
                "'_id' INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
                "'URI' TEXT NOT NULL ," + // 1: uri
                "'TAKE_DATE' INTEGER," + // 2: takeDate
                "'TITLE' TEXT," + // 3: title
                "'ABOUT' TEXT," + // 4: about
                "'LOCATION_ID' INTEGER NOT NULL );"); // 5: locationId
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'PHOTO'";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, Photo entity) {
        stmt.clearBindings();
 
        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }
        stmt.bindString(2, entity.getUri());
 
        java.util.Date takeDate = entity.getTakeDate();
        if (takeDate != null) {
            stmt.bindLong(3, takeDate.getTime());
        }
 
        String title = entity.getTitle();
        if (title != null) {
            stmt.bindString(4, title);
        }
 
        String about = entity.getAbout();
        if (about != null) {
            stmt.bindString(5, about);
        }
        stmt.bindLong(6, entity.getLocationId());
    }

    @Override
    protected void attachEntity(Photo entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    /** @inheritdoc */
    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }    

    /** @inheritdoc */
    @Override
    public Photo readEntity(Cursor cursor, int offset) {
        Photo entity = new Photo( //
            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
            cursor.getString(offset + 1), // uri
            cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)), // takeDate
            cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // title
            cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // about
            cursor.getLong(offset + 5) // locationId
        );
        return entity;
    }
     
    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, Photo entity, int offset) {
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setUri(cursor.getString(offset + 1));
        entity.setTakeDate(cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)));
        entity.setTitle(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
        entity.setAbout(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
        entity.setLocationId(cursor.getLong(offset + 5));
     }
    
    /** @inheritdoc */
    @Override
    protected Long updateKeyAfterInsert(Photo entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }
    
    /** @inheritdoc */
    @Override
    public Long getKey(Photo entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override    
    protected boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "photos" to-many relationship of Location. */
    public List<Photo> _queryLocation_Photos(long locationId) {
        synchronized (this) {
            if (location_PhotosQuery == null) {
                QueryBuilder<Photo> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.LocationId.eq(null));
                queryBuilder.orderRaw("_id ASC");
                location_PhotosQuery = queryBuilder.build();
            }
        }
        Query<Photo> query = location_PhotosQuery.forCurrentThread();
        query.setParameter(0, locationId);
        return query.list();
    }

    private String selectDeep;

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getLocationDao().getAllColumns());
            builder.append(" FROM PHOTO T");
            builder.append(" LEFT JOIN LOCATION T0 ON T.'LOCATION_ID'=T0.'_id'");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }
    
    protected Photo loadCurrentDeep(Cursor cursor, boolean lock) {
        Photo entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        Location location = loadCurrentOther(daoSession.getLocationDao(), cursor, offset);
         if(location != null) {
            entity.setLocation(location);
        }

        return entity;    
    }

    public Photo loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();
        
        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);
        
        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }
    
    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<Photo> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<Photo> list = new ArrayList<Photo>(count);
        
        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<Photo> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    

    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<Photo> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
 
}
